<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import Hls from "hls.js";

const props = defineProps({
  src: {
    type: String,
    required: true
  }
});

const videoEl = ref<HTMLVideoElement | null>(null);
const loading = ref(true);
const errorMessage = ref<string | null>(null);
let hlsInstance: Hls | null = null;

const initPlayer = () => {
  if (!videoEl.value) return;

  // 销毁旧实例
  if (hlsInstance) {
    hlsInstance.destroy();
    hlsInstance = null;
  }

  loading.value = true;
  errorMessage.value = null;

  // 处理路径 - 确保从项目根目录开始
   const videoUrl = props.src.startsWith('http') 
    ? props.src  // 已经是完整URL，直接使用
    : props.src.startsWith('/') 
      ? `${window.location.origin}${props.src}` // 补全为绝对路径
      : `${window.location.origin}/${props.src.replace('./', '')}`; // 处理相对路径

  console.log('最终视频URL:', videoUrl); // 调试用

  if (Hls.isSupported()) {
    hlsInstance = new Hls({
      maxBufferLength: 30,
      enableWorker: true,
      xhrSetup: (xhr) => {
        xhr.withCredentials = false;
      }
    });

    hlsInstance.loadSource(videoUrl);
    hlsInstance.attachMedia(videoEl.value);

    hlsInstance.on(Hls.Events.MANIFEST_PARSED, () => {
      loading.value = false;
    });

    hlsInstance.on(Hls.Events.ERROR, (_, data) => {
      loading.value = false;
      if (data.fatal) {
        errorMessage.value = `播放错误: ${data.details}`;
      }
    });
  } else if (videoEl.value.canPlayType('application/vnd.apple.mpegurl')) {
    // Safari原生支持
    videoEl.value.src = videoUrl;
    videoEl.value.addEventListener('loadedmetadata', () => {
      loading.value = false;
    });
  } else {
    errorMessage.value = "浏览器不支持HLS播放";
    loading.value = false;
  }
};

onMounted(initPlayer);
onUnmounted(() => {
  if (hlsInstance) {
    hlsInstance.destroy();
  }
});
</script>

<template>
  <div class="video-player">
    <video
      ref="videoEl"
      controls
      playsinline
    ></video>
    <div v-if="loading">加载中...</div>
    <div v-if="errorMessage" class="error">{{ errorMessage }}</div>
  </div>
</template>

<style scoped>
.video-player {
  width: 100%;
  margin: 0 auto;
  height: auto;

}
.error {
  color: red;
  margin-top: 10px;
}
</style>